package top.lenjon.lib.controller;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import top.lenjon.lib.entity.UserDetail;
import top.lenjon.lib.model.LoginModel;
import top.lenjon.lib.model.ResponseModel;
import top.lenjon.lib.service.LoginService;
import top.lenjon.lib.service.impl.LogServiceImpl;
import top.lenjon.lib.service.impl.UserDetailServiceImpl;
import top.lenjon.lib.util.RedisUtil;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

/**
 * @Author whz
 * @Date 2020/11/8 22:34
 **/
@RestController
public class LoginController {
    @Autowired
    LoginService loginService;

    @Autowired
    RedisUtil redisUtil;

    @Autowired
    private LogServiceImpl logService;

    @Autowired
    private UserDetailServiceImpl userService;

    @PostMapping("/login")
    public ResponseModel login(@Valid @RequestBody LoginModel loginModel, HttpServletRequest request) {
        if (loginService.loginUser(loginModel)) {
            if (redisUtil.get(request.getHeader("token")) != null) {
                return ResponseModel.error("重复登录");
            }
            String token = loginService.generateToken(loginModel);
            if (loginModel.getType() != 0) {
                return ResponseModel.success("success", token);
            }
            UserDetail user = userService.getUserByUserName(loginModel.getUsername());
            if (logService.getLogExpiredLogOf(user.getId()).size() != 0) {
                user.setEnabled(false);
                userService.updateById(user);
                return ResponseModel.success("你有过期书籍，请处理", token);
            } else if (logService.getLogShouldBeRenewOf(user.getId()).size() != 0) {
                return ResponseModel.success("你有临期书籍，请尽快归还", token);
            } else {
                return ResponseModel.success("success", token);
            }
        } else {
            return ResponseModel.error("用户不存在或密码错误");
        }
    }

    @DeleteMapping("/logout")
    public ResponseModel logout(HttpServletRequest request) {
        if (loginService.logout(request)) {
            return ResponseModel.success("登出");
        }
        return ResponseModel.error("登出失败");
    }
}
